﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Toolbox;

namespace FremtidensPlejehjem_Server.Messaging
{
    public class Consumer
    {
        MessageQueue _channel;
        Producer _replyProducer;

        public Consumer(MessageQueue channel, MessageQueue replyChannel)
        {
            _channel = channel;
            _replyProducer = new Producer(replyChannel);

            _channel.ReceiveCompleted += new ReceiveCompletedEventHandler(channel_ReceiveCompleted);
            _channel.BeginReceive();
        }

        private void channel_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
        {
            MessageQueue mq = (MessageQueue)sender;
            Message message = mq.EndReceive(e.AsyncResult);
            message.Formatter = new XmlMessageFormatter(new String[] { "System.String,mscorlib" });
            
            Console.WriteLine("Received Message from " + _channel.QueueName);

            CommandMessage comMsg = GeneralTools.DeserializeMessage<CommandMessage>(message);

            FileInfo fInfo = new FileInfo(Directory.GetCurrentDirectory() + @"\FremtidensPlejehjem-Server.exe");

            Console.WriteLine("Invoking Process: " + comMsg.MethodName);

            _replyProducer.SendMessage(GeneralTools.InvokeMethod(fInfo, comMsg.MethodName, comMsg.ParameterArray, "Activity"), message.Label);
            
            mq.BeginReceive();
        }
    }
}
